using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.UI;
using System.IO;
using System.Web.Security;
using System.Configuration;

public partial class ImageManager : System.Web.UI.Page
{
    protected System.Web.UI.WebControls.Label lblData;
    protected string root;
    protected string Dir;
    protected void Page_Load(object sender, System.EventArgs e)
    {
        Dir = Server.MapPath(ResolveUrl("~/"));
        lblError.Text = "";
        if (!IsPostBack)
        {

            btnDelete.Attributes.Add("OnClick", "return btnDelete_Click()");
            BindData();
        }
    }
    private void BindData()
    {
        dgFile.DataSource = GetFiles();
        dgFile.DataKeyField = "type";
        dgFile.DataBind();
        lblCounter.Text = dgFile.Items.Count.ToString() + " object(s)";

    }
    protected DataTable GetFiles()
    {
        DirectoryInfo dirInfo = new DirectoryInfo(GetCurDir());
        FileInfo[] info = dirInfo.GetFiles();
        DirectoryInfo[] dirs = dirInfo.GetDirectories();
        DataTable dt = CreateDataSource();
        DataRow dr;
        foreach (DirectoryInfo dir in dirs)
        {
            dr = dt.NewRow();
            dr["filename"] = dir.Name;
            dr["size"] = "0";
            dr["type"] = "0";
            dt.Rows.Add(dr);
        }
        foreach (FileInfo file in info)
        {
            dr = dt.NewRow();
            dr["filename"] = file.Name;
            dr["size"] = (int)file.Length / 1024;
            dr["type"] = "1";
            dr["modified"] = DateTime.Parse(file.LastWriteTime.ToString()).ToString("MM/dd/yyyy h:mm tt");
            dt.Rows.Add(dr);
        }
        dt.AcceptChanges();
        return dt;
    }
    protected DataTable CreateDataSource()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("filename", typeof(string));
        dt.Columns.Add("size", typeof(int));
        dt.Columns.Add("type", typeof(int));
        dt.Columns.Add("modified", typeof(string));
        return dt;
    }
    private String GetCurDir()
    {
        object obj = ViewState["curDir"];
        if (obj == null)
        {
            return Dir;

        }
        else
        {
            return (string)obj;
        }

    }
    private void SetCurDir(string dir)
    {
        ViewState["curDir"] = dir;
    }
    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }

    /// <summary>
    ///		Required method for Designer support - do not modify
    ///		the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.btnGoUp.Click += new System.Web.UI.ImageClickEventHandler(this.btnGoUp_Click);
        this.btnDelete.Click += new System.Web.UI.ImageClickEventHandler(this.btnDelete_Click);
        this.dgFile.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgFile_ItemCommand);
        this.dgFile.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgFile_CancelCommand);
        this.dgFile.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgFile_EditCommand);
        this.dgFile.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgFile_SortCommand);
        this.dgFile.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgFile_UpdateCommand);
        this.dgFile.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgFile_ItemDataBound);
        this.Imagebutton1.Click += new System.Web.UI.ImageClickEventHandler(this.Imagebutton1_Click);

    }
    #endregion

    private void dgFile_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.EditItem)
        {
            System.Web.UI.WebControls.Image imgType = (System.Web.UI.WebControls.Image)e.Item.FindControl("imgType");
            PlaceHolder plhImgEdit = (PlaceHolder)e.Item.FindControl("plhImgEdit");
            LinkButton lnkName = (LinkButton)e.Item.FindControl("lnkName");
            System.Web.UI.WebControls.HyperLink imgACL = (System.Web.UI.WebControls.HyperLink)e.Item.FindControl("imgACL");



            //HyperLInk for Edit Text
            HyperLink hlImgEdit = new HyperLink();
            hlImgEdit.ImageUrl = "images/btnEdit.gif";
            hlImgEdit.NavigateUrl = "ImageCode.aspx?ID=" + GetCurDir() + "\\" + DataBinder.Eval(e.Item.DataItem, "filename");
            //----

            int type = int.Parse(System.Web.UI.DataBinder.Eval(e.Item.DataItem, "type", "{0}"));
            if (type == 0)
            {
                imgType.ImageUrl = "images/folder.jpg";
                e.Item.Cells[2].Text = "";
                e.Item.Cells[3].Text = "";
            }
            else
            {
                string name = System.Web.UI.DataBinder.Eval(e.Item.DataItem, "filename", "{0}").Trim().ToLower();

                if (name.Trim().ToLower().EndsWith(".txt") || name.Trim().ToLower().EndsWith("vb") || name.Trim().ToLower().EndsWith("cs"))
                {
                    imgType.ImageUrl = "images/fileText.jpg";

                }
                else if (name.Trim().ToLower().EndsWith(".jpg") || name.Trim().ToLower().EndsWith(".gif") || name.Trim().ToLower().EndsWith(".bmp"))
                {
                    imgType.ImageUrl = "images/filejpeg.jpg";
                }
                else if (name.Trim().ToLower().EndsWith(".html") || name.Trim().ToLower().EndsWith(".htm"))
                {
                    plhImgEdit.Controls.Add(hlImgEdit);
                    imgType.ImageUrl = "images/filehtml.jpg";
                }
                else if (name.Trim().ToLower().EndsWith(".asp") || name.Trim().ToLower().EndsWith(".aspx") || name.Trim().ToLower().EndsWith(".php"))
                {
                    plhImgEdit.Controls.Add(hlImgEdit);
                    imgType.ImageUrl = "images/fileasp.jpg";
                }
                else
                {
                    imgType.ImageUrl = "images/fileunknown.jpg";

                }

            }
        }
    }

    private void dgFile_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
        if (e.CommandName == "ItemClicked")
        {
            dgFile.EditItemIndex = -1;
            LinkButton lnkName = (LinkButton)e.Item.FindControl("lnkName");
            int type = int.Parse(dgFile.DataKeys[e.Item.ItemIndex].ToString());
            if (type == 0)
            {

                SetCurDir(Path.Combine(GetCurDir(), lnkName.Text));


            }
            else
            {
                string filename = Path.Combine(GetCurDir(), lnkName.Text);
                Response.AddHeader("Content-Disposition", "attachment; filename=" + lnkName.Text.Trim());
                Response.WriteFile(filename);
                Response.End();

            }
            try
            {
                BindData();
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }



    }

    private void dgFile_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
        try
        {
            TextBox txtEditName = (TextBox)e.Item.FindControl("txtEditName");
            if (txtEditName.Text.Trim().Length < 1)
                return;

            int type = int.Parse(dgFile.DataKeys[e.Item.ItemIndex].ToString());
            if (type == 0)
            {
                Directory.Move(Path.Combine(GetCurDir(), Path.GetFileName(ViewState["lastSelection"].ToString())), Path.Combine(GetCurDir(), Path.GetFileName(txtEditName.Text)));
            }
            else
            {
                File.Move(Path.Combine(GetCurDir(), Path.GetFileName(ViewState["lastSelection"].ToString())), Path.Combine(GetCurDir(), Path.GetFileName(txtEditName.Text)));
            }
            dgFile.EditItemIndex = -1;
            BindData();
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }

    private void dgFile_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
        dgFile.EditItemIndex = e.Item.ItemIndex;
        LinkButton lnkName = (LinkButton)e.Item.FindControl("lnkName");
        ViewState["lastSelection"] = lnkName.Text;
        BindData();
    }

    private void dgFile_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
        dgFile.EditItemIndex = -1;
        BindData();
    }

    private void btnGoUp_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        MoveUp();
        BindData();
    }
    private void MoveUp()
    {
        if (!CanMoveUp())
            return;
        string dir = Path.GetDirectoryName(GetCurDir());
        SetCurDir(dir);
    }
    protected bool CanMoveUp()
    {
        string dir = GetCurDir().ToLower().Trim();

        if (dir.Length > Dir.Length)
            return true;
        return false;
    }
    private void DeleteItem(DataGridItem e)
    {
        LinkButton lnkName = (LinkButton)e.FindControl("lnkName");
        int type = int.Parse(dgFile.DataKeys[e.ItemIndex].ToString());
        if (type == 0)
        {
            Directory.Delete(Path.Combine(GetCurDir(), lnkName.Text), true);
        }
        else
        {
            File.Delete(Path.Combine(GetCurDir(), lnkName.Text));
        }
    }

    private void btnDelete_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        try
        {
            bool yes = false;
            foreach (DataGridItem dgi in dgFile.Items)
            {
                CheckBox chkChecked = (CheckBox)dgi.FindControl("chkChecked");
                if (chkChecked.Checked)
                {
                    yes = true;
                    DeleteItem(dgi);
                }
            }
            if (yes)
            {
                dgFile.CurrentPageIndex = 0;
                dgFile.EditItemIndex = -1;
                BindData();
            }
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }

    private void Imagebutton1_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        try
        {
            Directory.CreateDirectory(Path.Combine(GetCurDir(), Path.GetFileName(txtNewDirectory.Text)));
            txtNewDirectory.Text = "";
            BindData();
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }

    private void dgFile_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
    {
        if (ViewState["SortBy"] == null)
        {
            ViewState["SortBy"] = "ASC";
        }
        else if (ViewState["SortBy"].ToString().Equals("ASC"))
        {
            ViewState["SortBy"] = "DESC";
        }
        else
        {
            ViewState["SortBy"] = "ASC";
        }

        dgFile.Columns[1].HeaderText = "FileName";
        dgFile.Columns[2].HeaderText = "Size(KB)";
        dgFile.Columns[3].HeaderText = "Modified";
        for (int i = 0; i < dgFile.Columns.Count; i++)
        {
            if (dgFile.Columns[i].SortExpression.Trim().Equals(e.SortExpression.Trim()))
            {

                if (ViewState["SortBy"].ToString().Trim().Equals("ASC"))
                {
                    dgFile.Columns[i].HeaderText = dgFile.Columns[i].HeaderText + "<span style='font-family:webdings;'>5</span>";
                }
                else
                {
                    dgFile.Columns[i].HeaderText = dgFile.Columns[i].HeaderText + "<span style='font-family:webdings;'>6</span>";
                }

            }
        }

        DataView dv = new DataView(GetFiles());
        dv.Sort = e.SortExpression + " " + ViewState["SortBy"];
        dgFile.DataSource = dv;
        dgFile.DataBind();

    }

    protected void btnUpload_Click(object sender, System.EventArgs e)
    {
        try
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                if (Request.Files[i].FileName.Trim().Length > 0)
                {
                    HttpPostedFile file = Request.Files[i];
                    if (file != null && file.FileName.Length > 0)
                        file.SaveAs(Path.Combine(GetCurDir(), Path.GetFileName(file.FileName)));
                }
            }
            BindData();
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }
}